package com.gp.study.mybatis.plugin;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.gp.study.mybatis.annotation.Intercepts;
/**
 * 拦截器包装类，持有拦截器对象，才能去拦截啊啊
 * @author USER
 *
 */
public class Plugin implements InvocationHandler {
	
	private Object target;
	private Interceptor interceptor;
	
	public Plugin(Object target,Interceptor interceptor) {
		this.target = target;
		this.interceptor = interceptor;
	}
	
	/**
	 * 对被代理对象代理，返回代理对象
	 * @param obj
	 * @param interceptor
	 * @return
	 */
	public static Object wrap(Object obj, Interceptor interceptor) {
		Class<? extends Object> clz = obj.getClass();
		return Proxy.newProxyInstance(
					clz.getClassLoader(),
					clz.getInterfaces(),
					new Plugin(obj, interceptor));
	}
	

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		// 自定义的插件上有@Intercepts注解，指定了拦截的方法
        if (interceptor.getClass().isAnnotationPresent(Intercepts.class)) {
            // 如果是被拦截的方法，则进入自定义拦截器的逻辑
            if (method.getName().equals(interceptor.getClass().getAnnotation(Intercepts.class).value())) {
                return interceptor.intercept(new Invocation(target, method, args));
            }
        }
		return method.invoke(target, args);
	}

}
